//
//  NewspaperInfoViewController.m
//  JianChaRiBao
//
//  Created by 常兴宇 on 13-10-29.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "NewspaperInfoViewController.h"
#import "AppDelegate.h"
#import "PicVersion.h"
#import "NewspaperTitleCell.h"
#import "NewspaperDesCell.h"
#import "NewspaperPicDesViewController.h"
#import "NewspaperSingleArticleViewController.h"
#import "DownloadArticle.h"
#import "ActivateViewController.h"

@interface NewspaperInfoViewController ()
{
    ActivateViewController *accountViewCon;
    NSMutableArray * textVersionArray;
    NSString * item_id;
}
@end

@implementation NewspaperInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        shouldSwipeBack = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(homePageActived) name:@"HomePageActived" object:nil];
    }
    return self;
}
- (IBAction)backButtonClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    downloadButton.hidden = YES;
    
    if (self.titleStr) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.baseInfo];
        [dic setObject:self.titleStr forKey:@"pub_date"];
        self.baseInfo = dic;
    }
    
    item_id = [[self.baseInfo objectForKey:@"item_id"]retain];

    NSLog(@"baseInfo:%@",self.picVersionArray);
    if (self.isHomePage) {
        backButton.hidden = YES;
        [self getHomePageData];
    }else{
        
        [self getPicData];

    }
    
    //遮盖试图点击事件
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    [MaskView addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideMenu)];
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [MaskView addGestureRecognizer:swipeGesture];
    [swipeGesture release];
    
    //阴影效果
    MainView.layer.shadowColor = [UIColor blackColor].CGColor;
    MainView.layer.shadowOpacity = 0.45;
    MainView.layer.shadowOffset = CGSizeMake(0, 6);
    MainView.layer.shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 320, 548)].CGPath;
    MainView.layer.masksToBounds = NO;
    
    accountViewCon = [[ActivateViewController alloc]initWithNibName:@"ActivateViewController" bundle:nil];
    [ActiveView addSubview:accountViewCon.view];

    
    
}
-(void)getPicData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getNewspaperPicVersions:[_baseInfo objectForKey:@"item_id"] imageType:@""];
        NSLog(@"data:%@",data);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.picVersionArray = [data objectForKey:@"result"];
                [self reloadView];
            }
        });
    });

}
-(void)homePageActived{
    [self getData];
}
- (void)hideMenu
{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = 0;
        MainView.frame = rect;
        MaskView.alpha = 0;
    }];
    [self becomeFirstResponder];
    //如果激活成功刷新数据
    NSLog(@"endtime:%@",[[NSUserDefaults standardUserDefaults]objectForKey:EndTime]);
    if ([[NSUserDefaults standardUserDefaults]objectForKey:EndTime]) {
        [self getData];
    }
}
-(void)showActiveView{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = MainView.frame;
        rect.origin.x = -280;
        MainView.frame = rect;
        
        MaskView.alpha = 0.3;
    }];
    
}

-(void)getHomePageData{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] getHomePage];
        NSLog(@"obj:%@",obj);
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([obj isKindOfClass:[NSDictionary class]] && [[obj objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.titleStr = [[[obj objectForKey:@"result"] objectAtIndex:0] objectForKey:@"volume"];
                self.picVersionArray = [[NSMutableArray alloc]initWithArray:[[[obj objectForKey:@"result"] objectAtIndex:0] objectForKey:@"pages_list"]];
                item_id = [[[[obj objectForKey:@"result"] objectAtIndex:0] objectForKey:@"item_id"]retain];
                NSLog(@"array:%@",self.picVersionArray);
                if (item_id && self.titleStr) {
                    self.baseInfo = @{@"item_id":item_id,@"pub_date":self.titleStr};
                }
            }

            [self reloadView];
        });
    });

}

- (void)reloadView{
    titleLabel.scrollType = ScrollSingle;
    titleLabel.font = [UIFont systemFontOfSize:21.0f];
    titleLabel.text = [NSString stringWithFormat:@"医师报%@",self.titleStr];
    [titleLabel startScroll];
    
    picVersionsButton.selected = YES;
    picGridView.layoutDirection = AQGridViewLayoutDirectionHorizontal;
    picGridView.pagingEnabled = YES;
    picGridView.requiresSelection = NO;
    picGridView.showsHorizontalScrollIndicator = NO;
    picGridView.showsVerticalScrollIndicator = NO;
    [picGridView reloadData];
    [picGridView setContentOffset:CGPointMake(320 * self.index, 0) animated:NO];
}


- (IBAction)picButtonClicked:(id)sender {
    picVersionsButton.selected = YES;
    textVersionsButton.selected = NO;
    picView.hidden = NO;
    textTableView.hidden = YES;
}
- (IBAction)textButtonClicked:(id)sender {
    if (!textVersionArray || textVersionArray.count == 0) {
        [self getData];
    }
    picVersionsButton.selected = NO;
    textVersionsButton.selected = YES;
    picView.hidden = YES;
    textTableView.hidden = NO;

}
- (IBAction)downloadButtonClicked:(id)sender {
    NSLog(@"%@",textVersionArray);
    if (![ActivateManager shareManager].isActivated) {
        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"您尚未激活"]autorelease];
        [abp show];
        return;
    }
    [[DownloadArticle shareDownloadArticle] downloadNewspaperWithArray:textVersionArray info:self.baseInfo];
    downloadButton.enabled = NO;
}

-(void)getData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (item_id && item_id.length != 0) {
            id obj = [[DataRequest sharedRequest] getNewspaperTextVersions:item_id];
            if ([obj isKindOfClass:[NSDictionary class]] && [[obj objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                textVersionArray = [[NSMutableArray alloc] initWithArray:[obj objectForKey:@"result"]];
            }

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            NSLog(@"array:%@",textVersionArray);
            [textTableView reloadData];
            downloadButton.hidden = NO;
        });
    });

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return textVersionArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        static NSString * cellID = @"cellID";
        NewspaperTitleCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NewspaperTitleCell" owner:self options:0]lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.baseInfo = dict;
        [cell updateDisplay];
        return cell;

    }else{
        static NSString * cellID = @"cellID1";
        NewspaperDesCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NewspaperDesCell" owner:self options:0]lastObject];
        }
        
        cell.baseInfo = dict;
        [cell updateDisplay];
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        return 40;
    }else{
        CGSize size = [[dict objectForKey:@"page_name"] sizeWithFont:[UIFont systemFontOfSize:17.0f] constrainedToSize:CGSizeMake(310, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
//        NSLog(@"high:%f",size.height);
        return size.height + 10;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dict = [textVersionArray objectAtIndex:indexPath.row];
    if ([[dict objectForKey:@"is_page"] boolValue]) {
        NSLog(@">>>>>>>>>>");
        return;
    }else{

        if ([ActivateManager shareManager].isFree || [ActivateManager shareManager].isActivated) {
            NewspaperSingleArticleViewController * newspaperSingleArticleViewController = [[[NewspaperSingleArticleViewController alloc]initWithNibName:@"NewspaperSingleArticleViewController" bundle:nil]autorelease];
//            newspaperSingleArticleViewController.baseInfo = dict;
            newspaperSingleArticleViewController.titleStr = self.titleStr;
            newspaperSingleArticleViewController.contentArray = textVersionArray;
            newspaperSingleArticleViewController.currentIndex = indexPath.row;
            [[UIApplication rootNavController] pushViewController:newspaperSingleArticleViewController animated:YES];
        }else{
            ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"您尚未激活"]autorelease];
            [abp show];
            if (self.isHomePage) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowActiveView" object:nil];
            }else{
                [self showActiveView];
            }

        }
    }
}


- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView
{
    return self.picVersionArray.count;
}

-(AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index{
    static NSString * cellID = @"cellID";
    PicVersion * cell = (PicVersion *)[gridView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[PicVersion alloc]initWithFrame:CGRectMake(25, 30, picGridView.bounds.size.width, picGridView.bounds.size.height) reuseIdentifier:cellID];
    }
    cell.baseInfo = [_picVersionArray objectAtIndex:index];
    cell.index = index;
    cell.viewController = self;
    if (self.isHomePage) {
        [cell updateDisplayWithImageStr:@"cover_img" text:[[[_picVersionArray objectAtIndex:index] objectForKey:@"page_number"] integerValue]];

    }else{
        [cell updateDisplayWithImageStr:@"image" text:[[[_picVersionArray objectAtIndex:index] objectForKey:@"page_number"] integerValue]];
    }
//    NSLog(@"array:%@",self.picVersionArray);
    return cell;
}
- (CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView
{
    return picGridView.bounds.size;//CGSizeMake(320, [UIScreen mainScreen].bounds.size.height - 95);
}
- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index{
    
    
    [self showIndex:index];
//    [self.navigationController pushViewController:newspaperPicDesViewController animated:YES];
}

//- (void)didSelectCell:(NSNotification *)notification
//{
//    int index = [notification.object integerValue];
//    [self showIndex:index];
//}

- (void)showIndex:(int)index
{
    NewspaperPicDesViewController * newspaperPicDesViewController = [[[NewspaperPicDesViewController alloc]initWithNibName:@"NewspaperPicDesViewController" bundle:nil]autorelease];
    newspaperPicDesViewController.titleStr = self.titleStr;
    newspaperPicDesViewController.item_id = item_id;
    newspaperPicDesViewController.pageNumber = [[self.picVersionArray objectAtIndex:index] objectForKey:@"page_number"];
    NSLog(@"rootNavController>>>>%@",[UIApplication rootNavController]);
    [[UIApplication rootNavController] pushViewController:newspaperPicDesViewController animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [titleLabel release];
    [picVersionsButton release];
    [textVersionsButton release];
    [downloadButton release];
    [picGridView release];
    [textTableView release];
    [picView release];
    [backButton release];
    [ActiveView release];
    [MainView release];
    [MaskView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [titleLabel release];
    titleLabel = nil;
    [picVersionsButton release];
    picVersionsButton = nil;
    [textVersionsButton release];
    textVersionsButton = nil;
    [downloadButton release];
    downloadButton = nil;
    [picGridView release];
    picGridView = nil;
    [textTableView release];
    textTableView = nil;
    [picView release];
    picView = nil;
    [backButton release];
    backButton = nil;
    [super viewDidUnload];
}
@end
